import { defineEventHandler, readBody } from 'h3'
import redis from '../util/redis'
import { recordLog } from '../util/log'

// POST /api/randomnames with JSON { key: string, names: string[] | string }
export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event) as any
    const key = body?.key
    let names = body?.names

    if (!key || typeof key !== 'string') {
      event.node.res.statusCode = 400
      return { status: 400, message: 'missing key' }
    }

    if (!names) names = []
    if (typeof names === 'string') {
      names = names.split(/\r?\n/).map((s: string) => s.trim()).filter(Boolean)
    }
    if (!Array.isArray(names)) {
      event.node.res.statusCode = 400
      return { status: 400, message: 'names must be array or newline string' }
    }

    try {
      const ttl = 7 * 24 * 3600 // 7 days
      const payload = JSON.stringify(names)
      // ioredis set with EX
      await (redis as any).set(key, payload, 'EX', ttl)
      await recordLog(event as any, { message: `randomnames: set key=${key} count=${names.length} ttl=${ttl}`, userId: 0 })
      return { status: 'ok', key, count: names.length, ttl }
    } catch (err: any) {
      event.node.res.statusCode = 500
      await recordLog(event as any, { message: `randomnames: redis set failed ${String(err)}`, userId: 0 })
      return { status: 500, message: 'redis set failed', error: String(err) }
    }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `randomnames: internal error ${String(err)}`, userId: 0 })
    return { status: 500, message: 'internal error', error: String(err) }
  }
})
